package com.lin.lazybone.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by mr.lin on 2017/10/17.
 * 描述：    工具统一类
 */

public class UtilTools
{
    //保存图片到shareutils
    public static void putImageToShare(Context mContext, ImageView imageView) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        //第一步：将Bitmap压缩成字节数组输出流
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
        //第二步：利用Base64将我们的字节数组输出流转换成String
        byte[] byteArray = byStream.toByteArray();
        String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        //第三步：将String保存shareUtils
        ShareUtils.putString(mContext, "image_title", imgString);
    }

    //读取图片
    public static void getImageToShare(Context mContext, ImageView imageView) {
        //1.拿到string
        String imgString = ShareUtils.getString(mContext, "image_title", "");
        if (!imgString.equals("")) {
            //2.利用Base64将我们string转换
            byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
            ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
            //3.生成bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(byStream);
            imageView.setImageBitmap(bitmap);
        }
    }

    //获取时间差
    public static String getTime(String time)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            Date date = formatter.parse(time);
            //Date curDate =  new Date(System.currentTimeMillis());
            long timec = (System.currentTimeMillis() - date.getTime())/1000;

            if (timec < 60)
            {
                return "发布于" + timec + "秒前";
            }else
            {
                int t = (int) (timec/60);
                if (t < 60)
                {
                    return "发布于" + t + "分钟前";
                }else
                {
                    int t2 = t/60;
                    if (t2 < 24)
                    {
                        return "发布于" + t2 + "小时前";
                    }else
                    {
                        int t3 = t2/24;
                        return "发布于" + t3 + "天前";
                    }
                }
            }

        } catch (ParseException e)
        {
            e.printStackTrace();
        }

        return null;
    }

}
